<?php 
namespace app\model;

use think\model;
use think\facade\Cache;
use think\facade\Db;

class Cat2Model extends Model 
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'cat2';
    // 设置当前模型的数据库连接
    //protected $connection = 'db_config';
    //protected $pk = 'id';
    protected $cat_temp=[];    

    // 模型初始化
    protected static function init()    {

    }

    //
    protected function init_cat($status=''){
        $cats =[];// Cache::get('cats');
        if(!$cats && !$this->cat_temp){
            $list = Db::table('cat2');
            if($status) $list=$list->where('status',1);
            $list = $list->order('sort')->select();

            $cats=[];
            foreach($list as $cat){
                $cat['hasChildren']=0;
                $cats[$cat['id']] = $cat;

            }
            $this->cat_temp = $cats;
            //Cache::set('cats',$cats,120);
        } 
        return $cats;
    }


    //初始化部门树
    public function catTree($status=''){
        $list = $this->init_cat($status); //halt($list);
        //建立一个cat数组,保存处理过的类别

        $cat[1]=$list[1]; 
        $this->getSubCat(1,$cat,1);

        return $cat;
    }

   //递归取得子类
    public function getSubCat($id,&$arr=[],$deep=0){

        foreach($this->cat_temp as $k=>$d){
            if($d['fid']==$id){
                $arr[$id]['hasChildren']=1;
                $d['deepth'] += $deep;
                $arr[$k] = $d;
                $this->getSubCat($d['id'],$arr,$deep+1);
            }
        }

        return $arr;
    }


}

